from django import forms
from django.core.exceptions import ValidationError

from oracle.models import ORole
from oracle.utils.encryption import gen_md5
from supergirl.models import UserInfo, Department, Gender
from gideon.service.starlabs import GideonModelForm, GideonForm


class UserInfoAddModelForm(GideonModelForm):
    username = forms.RegexField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'USERNAME'}),
        max_length=30,
        regex=r'^[\w.@+-]+$',
        strip=True,
        label="用户名",
        error_messages={
            'invalid': "该值只能包含字母、数字和字符@/./+/-/_",
            'required': "用户名未填",
        }
    )
    password = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'PASSWORD'}),
        strip=True,
        label="密码",
        error_messages={
            'required': "密码未填"
        }
    )
    confirm_password = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'REPASSWORD'}),
        strip=True,
        label="确认密码",
        error_messages={
            'required': "确认密码未填"
        }
    )
    nickname = forms.CharField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'REAL NAME'}),
        max_length=30,
        strip=True,
        label="姓名",
        error_messages={
            'required': "姓名未填",
        }
    )
    gender = forms.ChoiceField(
        choices=Gender.choices,
        widget=forms.widgets.Select(),
        label="性别",
        initial=0,
    )
    phone = forms.RegexField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'PHONE'}),
        max_length=11,
        regex=r'^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$',
        strip=True,
        label="手机号码",
        error_messages={
            'invalid': "该值只能为11位手机号",
            'required': "手机号码未填",
        }
    )
    email = forms.EmailField(
        required=True,
        label="邮箱",
        widget=forms.widgets.EmailInput(attrs={'placeholder': 'EMAIL ADDRESS'}),
        error_messages={
            'invalid': "email格式错误",
            'required': 'email未填'
        }
    )
    depart = forms.ModelChoiceField(
        required=True,
        widget=forms.widgets.Select(),
        label="所属部门",
        queryset=Department.objects.all(),
        to_field_name="key",
        empty_label="选择部门",
        error_messages={
            "required": "部门必须指定",
            "invalid_choice": "没有选项定义，请选择一个符合要求的选项"
        }
    )
    roles = forms.ModelMultipleChoiceField(
        label="拥有角色",
        widget=forms.widgets.SelectMultiple(),
        required=False,
        queryset=ORole.objects.all(),
        to_field_name="key",
    )

    class Meta:
        model = UserInfo
        fields = ['username', 'password', 'confirm_password', 'nickname', 'gender', 'phone', 'email', 'depart', 'roles', "level"]

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password and password != confirm_password:
            raise ValidationError('密码输入不一致！')
        return confirm_password

    def clean(self):
        if not self.has_error('password') and not self.has_error('confirm_password'):
            password = self.cleaned_data['password']
            self.cleaned_data['password'] = gen_md5(password)
        return self.cleaned_data


class UserInfoChangeModelForm(GideonModelForm):
    username = forms.RegexField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'USERNAME'}),
        max_length=30,
        regex=r'^[\w.@+-]+$',
        strip=True,
        label="用户名",
        error_messages={
            'invalid': "该值只能包含字母、数字和字符@/./+/-/_",
            'required': "用户名未填",
        }
    )
    nickname = forms.CharField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'REAL NAME'}),
        max_length=30,
        strip=True,
        label="姓名",
        error_messages={
            'required': "姓名未填",
        }
    )
    gender = forms.ChoiceField(
        choices=((0, '未知'), (1, '男'), (2, '女'),),
        widget=forms.widgets.Select(),
        label="性别",
        initial=0,
    )
    phone = forms.RegexField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'PHONE'}),
        max_length=11,
        regex=r'^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$',
        strip=True,
        label="手机号码",
        error_messages={
            'invalid': "该值只能为11位手机号",
            'required': "手机号码未填",
        }
    )
    email = forms.EmailField(
        required=True,
        label="邮箱",
        widget=forms.widgets.EmailInput(attrs={'placeholder': 'EMAIL ADDRESS'}),
        error_messages={
            'invalid': "email格式错误",
            'required': 'email未填'
        }
    )
    depart = forms.ModelChoiceField(
        widget=forms.widgets.Select(),
        label="所属部门",
        queryset=Department.objects.all(),
        to_field_name="key",
        empty_label="选择部门",
        error_messages={
            "invalid_choice": "没有选项定义，请选择一个符合要求的选项"
        }
    )
    roles = forms.ModelMultipleChoiceField(
        label="拥有角色",
        widget=forms.widgets.SelectMultiple(),
        required=False,
        queryset=ORole.objects.all(),
        to_field_name="key",
    )

    class Meta:
        model = UserInfo
        fields = ['username', 'nickname', 'gender', 'phone', 'email', 'depart', 'roles']


class UserInfoResetPasswordForm(GideonForm):
    password = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'PASSWORD'}),
        strip=True,
        label="密码",
        error_messages={
            'required': "密码未填"
        }
    )
    confirm_password = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'REPASSWORD'}),
        strip=True,
        label="确认密码",
        error_messages={
            'required': "确认密码未填"
        }
    )

    def clean_confirm_password(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if password != confirm_password:
            raise ValidationError('密码输入不一致！')
        return confirm_password

    def clean(self):
        if not self.has_error('password') and not self.has_error('confirm_password'):
            password = self.cleaned_data['password']
            self.cleaned_data['password'] = gen_md5(password)
        return self.cleaned_data
